import { SettingOutlined } from '@ant-design/icons';
import { useCreation } from 'ahooks';
import { Button, Select, Tooltip } from 'antd';
import React, { useCallback, useMemo, useState } from 'react';
import { useContextSelector } from 'use-context-selector';

import {
  Prompt_QuoteTemplateList,
  Prompt_systemQuotePromptList,
  Prompt_userQuotePromptList,
} from '@/common';
import FormLabel from '@/components/MyBox/FormLabel';
import MyModal from '@/components/MyModal';
import PromptEditor from '@/components/Textarea/PromptEditor';
import MyTooltip from '@/components/tooltip';
import QuestionTip from '@/components/tooltip/QuestionTip';
import PromptTemplate from '@/components/workflow/PromptTemplate';
import { t } from '@/locales/i18n';
import { AppContext } from '@/pages/app/detail/context';
import { PromptTemplateItem } from '@/types/ai/type';
import {
  datasetQuoteValueDesc,
  NodeInputKeyEnum,
  WorkflowIOValueTypeEnum,
} from '@/types/workflow/constant';
import {
  AiChatQuotePrompt,
  AiChatQuoteRole,
  AiChatQuoteTemplate,
} from '@/types/workflow/template/system/aiChat';
import { AiChatQuoteRoleType } from '@/types/workflow/template/system/aiChat/type';
import { getWorkflowGlobalVariables } from '@/utils/workflow/utils';

import { WorkflowContext } from '../../../../../context';
import ValueTypeLabel from '../../ValueTypeLabel';

import Reference from './Reference';

import type { RenderInputProps } from '../type';

const EditModal = ({ onClose, ...props }: RenderInputProps & { onClose: () => void }) => {
  const { inputs = [], nodeId } = props;
  const onChangeNode = useContextSelector(WorkflowContext, (v) => v.onChangeNode);
  const nodeList = useContextSelector(WorkflowContext, (v) => v.nodeList);
  const [data, setData] = useState({
    quoteTemplate:
      inputs.find((input) => input.key === NodeInputKeyEnum.aiChatQuoteTemplate)?.value || '',
    quotePrompt:
      inputs.find((input) => input.key === NodeInputKeyEnum.aiChatQuotePrompt)?.value || '',
    quoteRole: (inputs.find((input) => input.key === NodeInputKeyEnum.aiChatQuoteRole)?.value ||
      'system') as AiChatQuoteRoleType,
  });
  const { appDetail } = useContextSelector(AppContext, (v) => v);

  const variables = useCreation(() => {
    const globalVariables = getWorkflowGlobalVariables({
      nodes: nodeList,
      chatConfig: appDetail.chatConfig,
    });

    return globalVariables;
  }, [nodeList]);

  const [selectTemplateData, setSelectTemplateData] = useState<{
    title: string;
    templates: PromptTemplateItem[];
  }>();
  const quoteTemplateVariables = useMemo(
    () => [
      {
        key: 'q',
        label: 'q',
        icon: 'core/app/simpleMode/variable',
      },
      {
        key: 'a',
        label: 'a',
        icon: 'core/app/simpleMode/variable',
      },
      {
        key: 'source',
        label: t('core.dataset.search.Source name'),
        icon: 'core/app/simpleMode/variable',
      },
      {
        key: 'sourceId',
        label: t('core.dataset.search.Source id'),
        icon: 'core/app/simpleMode/variable',
      },
      {
        key: 'index',
        label: t('core.dataset.search.Quote index'),
        icon: 'core/app/simpleMode/variable',
      },
      ...variables,
    ],
    [variables],
  );
  const quotePromptVariables = useMemo(
    () => [
      {
        key: 'quote',
        label: t('core.app.Quote templates'),
        icon: 'core/app/simpleMode/variable',
      },
      ...(data.quoteRole === 'user'
        ? [
            {
              key: 'question',
              label: t('core.module.input.label.user question'),
              icon: 'core/app/simpleMode/variable',
            },
          ]
        : []),
      ...variables,
    ],
    [variables, data.quoteRole],
  );

  const onSubmit = useCallback(
    (data: { quoteTemplate: string; quotePrompt: string; quoteRole: AiChatQuoteRoleType }) => {
      onChangeNode({
        nodeId,
        type: 'replaceInput',
        key: NodeInputKeyEnum.aiChatQuoteRole,
        value: {
          ...AiChatQuoteRole,
          value: data.quoteRole || 'system',
        },
      });
      onChangeNode({
        nodeId,
        type: 'replaceInput',
        key: NodeInputKeyEnum.aiChatQuoteTemplate,
        value: {
          ...AiChatQuoteTemplate,
          value: data.quoteTemplate,
        },
      });
      onChangeNode({
        nodeId,
        type: 'replaceInput',
        key: NodeInputKeyEnum.aiChatQuotePrompt,
        value: {
          ...AiChatQuotePrompt,
          value: data.quotePrompt,
        },
      });

      onClose();
    },
    [nodeId, onChangeNode, onClose],
  );

  const quotePromptTemplates =
    data.quoteRole === 'user' ? Prompt_userQuotePromptList : Prompt_systemQuotePromptList;

  return (
    <>
      <MyModal
        isOpen
        iconSrc="edit"
        title={t('Quote_prompt_setting')}
        w="100%"
        // h={['90vh', '85vh']}
        // maxW={['90vw', '700px']}
        isCentered
      >
        <div className="overflow-auto">
          <div className="flex items-center">
            <FormLabel>{t('dataset_quote_role')}</FormLabel>
            <QuestionTip className="ml-1 mr-5" title={t('dataset_quote_role_tip')} />
            <Select
              popupClassName="workflow-dropdown"
              value={data.quoteRole}
              options={[
                {
                  label: '系统提示词',
                  value: 'system',
                  description: t('dataset_quote_role_system_option_desc'),
                },
                {
                  label: '用户提示词',
                  value: 'user',
                  description: t('dataset_quote_role_user_option_desc'),
                },
              ]}
              onChange={(e) => {
                // setValue('quoteRole', e);
                setData({
                  ...data,
                  quoteRole: e,
                });
              }}
            />
            <div className="ml-5">
              {data.quoteRole === 'user' ? (
                <Tooltip title={t('quote_role_user_tip')} />
              ) : (
                <Tooltip title={t('quote_role_system_tip')} />
              )}
            </div>
          </div>
          <div className="mt-4">
            <div className="mb-1 flex">
              <FormLabel>{t('core.app.Quote templates')}</FormLabel>
              <QuestionTip
                className="ml-1"
                title={t('quote_content_tip', {
                  default: Prompt_QuoteTemplateList[0].value,
                })}
              />
              <div className="flex-1" />
              <div
                // {...selectTemplateBtn}
                className="cursor-pointer text-sm text-primary-500 hover:text-primary-600"
                onClick={() =>
                  setSelectTemplateData({
                    title: t('core.app.Select quote template'),
                    templates: Prompt_QuoteTemplateList,
                  })
                }
              >
                {t('common.Select template')}
              </div>
            </div>

            <PromptEditor
              variables={quoteTemplateVariables}
              minH={160}
              title={t('core.app.Quote templates')}
              placeholder={t('quote_content_placeholder')}
              value={data.quoteTemplate}
              onChange={(e) => {
                // setValue('quoteTemplate', e);
                setData({
                  ...data,
                  quoteTemplate: e,
                });
              }}
            />
          </div>
          <div className="mt-4">
            <div className="mb-1 flex">
              <FormLabel>{t('core.app.Quote prompt')}</FormLabel>
              <QuestionTip
                className="ml-1"
                title={t('quote_prompt_tip', {
                  default: quotePromptTemplates[0].value,
                })}
              />
            </div>
            <PromptEditor
              variables={quotePromptVariables}
              title={t('core.app.Quote prompt')}
              minH={300}
              placeholder={t('quote_prompt_tip', {
                default: quotePromptTemplates[0].value,
              })}
              value={data.quotePrompt}
              onChange={(e) => {
                // setValue('quotePrompt', e);
                setData({
                  ...data,
                  quotePrompt: e,
                });
              }}
            />
          </div>
        </div>
        <div className="ml-auto mt-4">
          <Button className="mr-2" onClick={onClose}>
            {t('common.Close')}
          </Button>
          <Button
            type="primary"
            onClick={() => {
              onSubmit(data);
            }}
          >
            {t('common.Confirm')}
          </Button>
        </div>
      </MyModal>
      {/* Prompt template */}
      {!!selectTemplateData && (
        <PromptTemplate
          title={selectTemplateData.title}
          templates={selectTemplateData.templates}
          onClose={() => setSelectTemplateData(undefined)}
          onSuccess={(e) => {
            const quoteVal = e.value;

            const promptVal = quotePromptTemplates.find((item) => item.title === e.title)?.value;

            // setValue('quoteTemplate', quoteVal);
            // setValue('quotePrompt', promptVal);
            setData({
              ...data,
              quoteTemplate: quoteVal,
              quotePrompt: promptVal,
            });
          }}
        />
      )}
    </>
  );
};

const SettingQuotePrompt = (props: RenderInputProps) => {
  // const { isOpen, onOpen, onClose } = useDisclosure();

  const [isOpen, setIsOpen] = useState(false);

  const onOpen = useCallback(() => setIsOpen(true), []);
  const onClose = useCallback(() => setIsOpen(false), []);

  const Render = useMemo(() => {
    return (
      <>
        <div className="nodrag relative flex cursor-default items-center">
          <div className="relative mr-2 font-medium">{t('core.module.Dataset quote.label')}</div>
          <ValueTypeLabel
            valueType={WorkflowIOValueTypeEnum.datasetQuote}
            valueDesc={datasetQuoteValueDesc}
          />

          <MyTooltip title={t('core.module.Setting quote prompt')}>
            <Button
              type="text"
              className="ml-1 w-[14px]"
              icon={<SettingOutlined />}
              style={{ color: '#000' }}
              onClick={onOpen}
            />
          </MyTooltip>
        </div>
        <div className="mt-1">
          <Reference {...props} />
        </div>

        {isOpen && <EditModal {...props} onClose={onClose} />}
      </>
    );
  }, [isOpen, onClose, onOpen, props]);

  return Render;
};

export default React.memo(SettingQuotePrompt);
